#include<iostream>
#include<vector>
#include<cstdio>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

const std::string gsep = " ";
std::vector<int> data;


int savebegin()
{
    std::string name = std::to_string(time(nullptr));//将文件名，命名为时间戳
    name+= ".backup";//后缀

    FILE *fp = fopen(name.c_str(),"w");
    if(fp == nullptr) return 1;
    //转成字符串，存到datastr+gsep空格
    std::string datastr;
    for(auto d : data)
    {
        datastr += std::to_string(d);//转成字符串
        datastr += gsep;
    }

    fputs(datastr.c_str()  , fp);//把datastr的字符串，写到文件里

    fclose(fp);
    return 0;
}
void save()
{
    pid_t id = fork();
    if(id == 0)//子进程
    {
        int code = savebegin();//子进程要完成的任务-备份
        exit(code);
    }
    int sun = 0;
    pid_t rid = waitpid(id,&sun,0);
    if(rid > 0)
    {
        int code = WEXITSTATUS(sun);//WEXITSTATUS获取子进程的退出码
        if(code == 0)printf("备份成功，退出码:%d \n",code);
        else printf("备份失败，退出码:%d \n",code);

    }
    else{
        perror("waitpid\n");
    }


}

int main()
{
    int cnt = 1;
    while(true)
    {
        data.push_back(cnt++);
        sleep(1);
        if(cnt % 10 == 0)
        {
            //每10秒，备份一次
            save();
        }
    }
    return 0;
}
